<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>QQ简易聊天框Vue</title>
    <link rel="stylesheet" href="css/chat.css">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<section id="chat">
    <div class="chatBody">
        <section v-for="(pValue, index) in messageList" :key="index">
            <div>
                <img :src="pValue.src">
            </div>
            <p>{{pValue.userName}}</p>
            <div class="chatContent">
                {{pValue.chatMessage}}
            </div>
        </section>
    </div>
    <div>
        <img src="images/icon.jpg">
    </div>
    <textarea class="chatText" v-model="chatInputText"></textarea>
    <div class="btn">
        <span id="close" @click="toClose">关闭(C)</span>
        <span id="send" @click="toSend">发送(S)</span>
    </div>
</section>
<script>
    new Vue({
        el: '#chat',
        data: {
            messageList: [],
            chatInputText: []
        },
        methods: {
            toSend() {
                var headImg = new Array("head01.jpg","head02.jpg","head03.jpg");
                var uName = new Array("时尚伊人","六月奇迹","松松");

                if (this.chatInputText.length > 0) {
                    var iNum = Math.floor(Math.random() * 3);
                    //随机获取头像和昵称
                    var headStr = "images/" + headImg[iNum];
                    //设置头像
                    var userName = uName[iNum];
                    //设置昵称
                    var chatStr = this.chatInputText;
                    //获取并设置当前输入的内容
                    this.messageList.unshift(
                        {
                            src: headStr,
                            userName: userName,
                            chatMessage: chatStr
                        }
                    );
                    // 重置输入框
                    this.chatInputText = '';
                } else {
                    alert('输入不能为空！！！')
                }
            },
            toClose() {
                this.messageList = [];
                this.chatInputText = '';
            }
        }
    });
</script>
</body>
</html>